import configobj
import os
import misc.quoteperiod as qp
import datetime as dt

class NavalaConfig:
    # Set at descendant's __init__()
    _filename = None
    
    _c = None
    
    def __init__(self):
        """Creates a ConfigObject object."""
        self._c = configobj.ConfigObj()
        self._c.filename = self._filename
        self.Reload()
    
    def Reload(self):
        """Creates if does not exist, reloads config."""
        self.CreateIfDoesNotExist()
        self._c.reload()
    
    def PopulateDefault(self):
        """Responsible for populating self._c"""
        raise NotImplementedError("Not implemented")
        
    def CreateIfDoesNotExist(self):
        """Creates config file if it does not exist yet."""
        if not os.path.isfile(self._filename):
            self.PopulateDefault()
            self._c.write()

    def _GetThing(self, *args):
        if len(args) == 1:
            return self._c[args[0]]
        elif len(args) == 2:
            return self._c[args[0]][args[1]]
        elif len(args) == 3:
            return self._c[args[0]][args[1]][args[2]]
        else:
            raise RuntimeError("Incorrect usage (pass 1-3 arguments, not %d)" % len(args))

    def GetAsDatetime(self, *args):
        return dt.datetime.strptime(self._GetThing(*args), "%Y-%m-%d %H:%M:%S")
        
    def GetRaw(self, *args):
        """Use this to get strings and lists."""
        return self._GetThing(*args)
            
    def GetEval(self, *args):
        """Use to get value as float, int, bool etc."""
        return eval(self._GetThing(*args))
    
    def Set(self, *args):
        if len(args) == 2:
            self._c[args[0]] = args[1]
        elif len(args) == 3:
            self._c[args[0]][args[1]] = args[2]
        elif len(args) == 4:
            self._c[args[0]][args[1]][args[2]] = args[3]
        else:
            raise RuntimeError("Incorrect usage (pass 2-4 arguments, not %d)" % len(args))
        self._c.write()

#class _Config_DB(NavalaConfig):
#    _filename = "config_db.cfg"
#    def PopulateDefault(self):
#        self._c["databaseName"] = '../../db/navala.h5' # Name of database file
#        
#class _Config_GUI(NavalaConfig):
#    _filename = "config_gui.cfg"
#    def PopulateDefault(self):
#        self._c["startDt"] = {}
#        for i in range(qp.yearly+1):
#            self._c["startDt"][qp.data[i]["varname"]] = qp.GetDefaultStart(i)
#        self._c["workStocksets"] = ["Watched Indexes", "Watched Companies"]

class _Config_All(NavalaConfig):
    _filename = "config.cfg"
    def PopulateDefault(self):
        self._c["databaseName"] = '../../db/navala.h5' # Name of database file
        self._c["workStocksets"] = ["Watched Indexes", "Watched Companies"]
        self._c["initialDt"] = {}
        for i in range(qp.yearly+1):
            self._c["initialDt"][qp.data[i]["varname"]] = qp.GetDefaultStart(i)
        self._c["screens"] = {}
        
#config_DB = _Config_DB()
#config_GUI = _Config_GUI()

# This is named like this because this "configs" module is imported as "con",
# then the variable is conveniently accessed as con.fig
fig = _Config_All()

allConfigs = [fig] #[config_DB, config_GUI]
for obj in allConfigs:
    obj.CreateIfDoesNotExist()
